package cn.cfoodc.sharding.config;

import org.apache.shardingsphere.sharding.algorithm.keygen.SnowflakeKeyGenerateAlgorithm;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
public class TransactionConfiguration {

    @Bean
    public PlatformTransactionManager txManager(final DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public JdbcTemplate jdbcTemplate(final DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    //配置雪花算法实例
    @Bean
    @Primary
    public SnowflakeKeyGenerateAlgorithm snowflakeKeyGenerateAlgorithm(){

        SnowflakeKeyGenerateAlgorithm snowflakeKeyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm();
        Properties properties = new Properties();
        properties.setProperty("worker-id","456");
//        properties.setProperty("max-vibration-offset","2");
//        properties.setProperty("max-tolerate-time-difference-milliseconds","11");
        snowflakeKeyGenerateAlgorithm.setProps(properties);
        snowflakeKeyGenerateAlgorithm.init();
        return snowflakeKeyGenerateAlgorithm;
    }
}
